package com.c78.fz.filters;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.c78.fz.common.result.Result;
import com.c78.fz.common.utils.JwtUtil;
import com.c78.fz.common.utils.WebUtils;
import com.c78.fz.mapper.AccoundMapper;
import com.c78.fz.model.dto.LoginUser;
import com.c78.fz.model.entity.Accound;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    AccoundMapper accoundMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(ObjectUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }
        try{
            Claims claims = JwtUtil.parseJWT(token);
            String userId = claims.getSubject();

            QueryWrapper<Accound> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            Accound accound = accoundMapper.selectOne(queryWrapper);

            String userInfoJson = accound.getUserInfo();
            LoginUser loginUser = JSONObject.parseObject(userInfoJson,LoginUser.class);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            filterChain.doFilter(request,response);
        }catch (Exception e){
            WebUtils.renderString(response, JSON.toJSONString(Result.error("token过期")));
        }
    }
}
